package io.renren.common.utils;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import io.renren.common.annotation.FieldNotes;
import io.renren.common.entity.infoLogEntity;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class common {

    public static final char UNDERLINE = '_';

    public static boolean isWindows() {
        return System.getProperty("os.name").toUpperCase().contains("WINDOWS");
    }

    /*
     * 正则验证
     * */
    public static boolean telVerifica(String phone){
        String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(17[013678])|(18[0,5-9]))\\d{8}$";
        if(phone.length() != 11){
            log.error("[SEND_SMS]：手机号码格式错误！");
            return false;
        }else{
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phone);
            return m.matches();
        }
    }

    /*
    * map里剔除所有跟日期没关系的键值对
    * */
    public static Map<String,Object> mapCulling(Map<String,Object> map){
        Map<String,Object> objectMap = new HashMap<>();

        for (Entry<String, Object> entry : map.entrySet()) {
            try {
                DateUtils.stringToDate(entry.getKey(),DateUtils.DATE_PATTERN);
                objectMap.put(entry.getKey(),entry.getValue());
            }catch (Exception e){
                e.getLocalizedMessage();
                System.out.println(e.getLocalizedMessage());
            }
        }
        return objectMap;
    }



    /*
    * map 循环，转换为 list<map<string,object>>
    * */
    public static List<Map<String,Object>> mapTransList(Map<String,Object> map){
        List<Map<String,Object>> list = new Vector<>();

        for (Entry<String, Object> entry : map.entrySet()) {
            Map<String,Object> objMap = new HashMap<>();
            objMap.put(entry.getKey(),entry.getValue());
            list.add(objMap);
        }

        return list;
    }

    public static void main(String[] args) {
        String sign = "{\"hoursMoney\":true,\"2020-08-31\":159.0,\"dateList\":[{\"2020-08-31\":131.0}],\"roomId\":747.0}";
        Gson gson = new Gson();

        Map<String, Object> map = gson.fromJson(sign, new TypeToken<HashMap<String, Object>>() {}.getType());

        Map<String, Object> mapCulling = mapCulling(map);
        System.out.println(mapCulling);
    }

    /*
    * 指定目录运行cmd命令
    * */
    public static boolean runtimeCmdExec(String cmd, String path) {
        Process proc;
        try {
            Runtime rt = Runtime.getRuntime();
            String builder = "cmd /c " +
                    path +
                    File.separator +
                    cmd;
            proc = rt.exec(builder);
            InputStream stderr = proc.getErrorStream();
            InputStreamReader isr = new InputStreamReader(stderr);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            int exitVal = proc.waitFor();
            return exitVal == 0;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /*
     * 查找数组里缺失的最小数字
     * */
    public static int searchMissingNumber2(List<Integer> arr){
        if (arr.size()== 0){
            return 1;
        }
        if (arr.size()== 1 && arr.get(0)>1){
            return 1;
        }
        arr.sort(Comparator.naturalOrder());
        int max =0;
        for(int i = 1;i < arr.size();i++){
            int d = arr.get(i)-arr.get(i-1);
            if (d != 1){
                System.out.println("missing number is:"+(arr.get(i)-1));
                return arr.get(i)-1;
            }
        }
        max = arr.get(arr.size() - 1) + 1;
        System.out.println("missing number is: "+max);
        return max;
    }

    /**
     * 把map的key转换成驼峰命名
     *
     * @param map
     * @return
     */
    public static Map<String, Object> toReplaceKeyLow(Map<String, Object> map) {
        Map<String, Object> re_map = new HashMap<>();
        for (Entry<String, Object> entry : map.entrySet()) {
            re_map.put(underlineToCamel(entry.getKey()), map.get(entry.getKey()));
        }
        map.clear();
        return re_map;
    }

    public static String underlineToCamel(String param) {
        if (param == null || "".equals(param.trim())) {
            return "";
        }
        int len = param.length();
        StringBuilder sb = new StringBuilder(len);
        for (int i = 0; i < len; i++) {
            char c = param.charAt(i);
            if (c == UNDERLINE) {
                if (++i < len) {
                    sb.append(Character.toUpperCase(param.charAt(i)));
                }
            } else {
                sb.append(Character.toLowerCase(param.charAt(i)));
            }
        }
        return sb.toString();
    }


    /*
     * 生成订单号
     * */
    public static String getOrderIdByTime() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String newDate = sdf.format(new Date());
        String result = "";
        Random random = new Random();
        for (int i = 0; i < 3; i++) {
            result += random.nextInt(10);
        }
        return newDate + result;
    }

    public static List<String> getBetweenDates(String start, String end, Boolean asc) {
        List<String> result = new ArrayList<String>();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date start_date = sdf.parse(start);
            Date end_date = sdf.parse(end);
            Calendar tempStart = Calendar.getInstance();
            tempStart.setTime(start_date);
            Calendar tempEnd = Calendar.getInstance();
            tempEnd.setTime(end_date);
            while (tempStart.before(tempEnd) || tempStart.equals(tempEnd)) {
                result.add(sdf.format(tempStart.getTime()));
                tempStart.add(Calendar.DAY_OF_YEAR, 1);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (!asc) {
            Collections.reverse(result);
        }
        return result;
    }

    /*
     * 如果后一位为.0就去除小数点
     * */
    public static String removeDecimalPoint(String str) {
        if (str.substring(str.length() - 2).equals(".0")) {
            str = str.substring(0, str.length() - 2);
        }
        return str;
    }

    /**
     * emoji表情替换
     *
     * @param source 原字符串
     * @return 过滤后的字符串
     */
    public static String filterEmoji(String source) {
        if (source != null && source.length() > 0) {
            return source.replaceAll("[\ud800\udc00-\udbff\udfff\ud800-\udfff]", "꧂");
        } else {
            return source;
        }
    }

    /*
    * 过滤html为存文本
    * */
    public static String delHTMLTag(String htmlStr){
        String regEx_script="<script[^>]*?>[\\s\\S]*?<\\/script>"; //定义script的正则表达式
        String regEx_style="<style[^>]*?>[\\s\\S]*?<\\/style>"; //定义style的正则表达式
        String regEx_html="<[^>]+>"; //定义HTML标签的正则表达式
        Pattern p_script=Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);
        Matcher m_script=p_script.matcher(htmlStr);
        htmlStr=m_script.replaceAll(""); //过滤script标签
        Pattern p_style=Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);
        Matcher m_style=p_style.matcher(htmlStr);
        htmlStr=m_style.replaceAll(""); //过滤style标签
        Pattern p_html=Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);
        Matcher m_html=p_html.matcher(htmlStr);
        htmlStr=m_html.replaceAll(""); //过滤html标签
        return htmlStr.trim(); //返回文本字符串
    }


    public static List<infoLogEntity> reedClass(Object o) {
        List<infoLogEntity> list = new ArrayList<>();
        Class<?> aClass = o.getClass();
        Field[] fields = aClass.getDeclaredFields();
        for (Field field : fields) {
            // 判断字段false注解是否存在
//            if (field.isAnnotationPresent(TableField.class)) {
//                TableField annotation = field.getAnnotation(TableField.class);
//                boolean exist = annotation.exist();
//                if (!exist){
//                    continue;
//                }
//            }
            infoLogEntity logEntity = new infoLogEntity();
            // 判断字段注解是否存在
            if (!field.isAnnotationPresent(FieldNotes.class)) {
                continue;
            }
            FieldNotes notes = field.getAnnotation(FieldNotes.class);
            String value = notes.value();
            logEntity.setNotes(value);
            // 如果不为空，设置可见性，然后返回
            field.setAccessible(true);
            String key = field.getName();
            Object val;
            try {
                val = field.get(o);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                continue;
            }
            if (String.valueOf(val) == null
                    || String.valueOf(val) .equals("")
                    || String.valueOf(val) .equals(" ")
                    || String.valueOf(val) .equals("null")
                    || key.equals("serialVersionUID")){
                continue;
            }
            logEntity.setContent(common.delHTMLTag(String.valueOf(val)));
            logEntity.setField(humpUtils.HumpToUnderline(key));
            //设置状态词汇
            String[] states = notes.state();
            if (states.length>0){
                int state = Integer.valueOf(common.delHTMLTag(String.valueOf(val)));
                logEntity.setContent(states[state]);
            }
            list.add(logEntity);
        }
        return list;
    }

    public static String getURLEncode(String url) {
        return URLEncoder.encode(url);
    }

    public static List<String> sellerIdList(String ids, Object sellerId) {
        String[] sellerIds = null;
        if (StringUtils.isEmpty(ids)) {
            return null;
        }
        if (StringUtils.isNotEmpty(ids)) {
            sellerIds = ids.split(",");
            sellerId = null;
        }
        if (null == sellerIds) {
            return null;
        }
        return Arrays.asList(sellerIds);
    }
}
